package com.youbug.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.system.entity.Dictionary;
import com.youbug.system.mapper.DictionaryMapper;
import com.youbug.system.service.IDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-02-12
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {

    private Map<String, Map<String, Dictionary>> dicCache = new HashMap<>();

    @Override
    public List<Dictionary> listByTypeCode(String typeCode) {

        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();

        wrapper.eq("type_code", typeCode);

        wrapper.orderByAsc("order_id");

        return this.list(wrapper);
    }

    @Override
    public Dictionary getOneByTypeAndCode(String typeCode, String itemCode) {
        // 暂时使用内存缓存
        Map<String, Dictionary> dicMap = dicCache.get(typeCode);
        if(null != dicCache.get(typeCode)){
            Dictionary dic = dicMap.get(itemCode);
            if(null != dic){
                return dic;
            }
        }

        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();

        wrapper.eq("type_code", typeCode);

        wrapper.eq("code", itemCode);

        Dictionary dictionary = this.getOne(wrapper);

        Map<String, Dictionary> dictionaryMap = dicCache.get(typeCode);

        if(null == dictionaryMap){

            Map<String, Dictionary> dicMapTemp = new HashMap<>();

            dicMapTemp.put(itemCode, dictionary);

            dicCache.put(typeCode, dicMapTemp);
        }else{
            dictionaryMap.putIfAbsent(itemCode, dictionary);
        }
        return dictionary;
    }
}
